package advertising

import (
	"encoding/json"
	"gitee.com/alex_li/amazon-rpt/internal/lwa"
	common "gitee.com/alex_li/amazon-rpt/internal/sdk/amazon"
	"github.com/lishimeng/go-log"
	"os"
)

type TokenFactory struct {
	Ads lwa.AccessToken `json:"ads,omitempty"`
}

var ft TokenFactory

var (
	knownProfile int64 = 3092463805242912
	appid              = ""
	secret             = ""
)

var tokenFile string

func loadEnv() {
	tokenFile = "tmp_ads_token.json"

	appid = os.Getenv("AWS_APP_ID")
	secret = os.Getenv("AWS_SECRET")
}

func saveToken(at lwa.AccessToken) {
	f, err := os.OpenFile(tokenFile, os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Info(err)
		return
	}
	defer func() {
		_ = f.Close()
	}()
	ft.Ads = at
	bs, err := json.Marshal(ft)
	_, err = f.WriteString(string(bs))
	if err != nil {
		log.Info("保持token失败:" + err.Error())
		log.Info(err)
		return
	}
}

func loadToken() (tf TokenFactory) {
	bs, err := os.ReadFile(tokenFile)
	if err != nil {
		log.Info("token文件不存在:" + tokenFile)
		return
	}
	err = json.Unmarshal(bs, &tf)
	if err != nil {
		log.Info("token内容错误:")
		log.Info(err)
		return
	}
	log.Info("reuse toke.")
	return
}

func createLwa(refreshToken string) *lwa.Client {
	log.Info("init sdk: %s[%s]", appid, secret)
	connector := lwa.New(appid, secret, refreshToken)
	return connector
}

func createApi() (c *Client) {
	loadEnv() // 初始化token

	at := loadToken()

	connector := createLwa(at.Ads.RefreshToken)

	c = New(WithLwa(connector, func(token lwa.AccessToken) {
		saveToken(token) // 保存token
	}), WithTokenErrorListener(func(clientId string, err error) {
		log.Info("token error:", err)
	}), WithMarketplace(common.Us, true),
		WithLwaToken(at.Ads),
		WithProfile(knownProfile),
	)
	return
}
